'use strict';

var _ = require('underscore');
var suquelizeService = require('../utils/sequelizeService');
var User = suquelizeService.models.User;
var resJson = require('../utils/resJson.js');
var Promise = require('bluebird');

var controller = {

};

controller.getUsers = {
  route: 'users',
  method: 'get',
  paramUrl: ['', '/:name'],
  action: function(req, res, next) {
    var getUser;
    if (_.isEmpty(req.params)) {
      getUser = User.fetch();
    } else {
      var name = req.params.name;
      getUser = User.findByLoginName(name);
    }
    getUser.then(function(_user) {
        return resJson(res, _user);
      })
      .catch(function(err) {
        return resJson(res, null, err);
      });
  }
};

controller.login = {
  method: 'post',
  action: function(req, res, next) {
    var user = req.session ? req.session.user : null;
    if (user) {
      return resJson(res, { isLogin: true });
    } else {
      var userObj = req.body.user;
      if (userObj) {
        User.findOne({
            where: {
              loginName: userObj.name
            }
          })
          .then(function(_user) {
            if (!_user || _.isEmpty(_user)) {
              return Promise.reject(new Error('用户名或密码不正确！'));
            } else {
              return _user.comparePassword(userObj.password);
            }
          })
          .then(function(user) {
            req.session.user = user;
            return resJson(res, { isLogin: true });
          })
          .catch(function(err) {
            return resJson(res, null, err);
          });
      } else {
        return resJson(res, null, '非法数据');
      }
    }
  }
};

controller.checkLogin = {
  method: 'get',
  action: function(req, res, next) {
    var user = req.session ? req.session.user : null;
    if (user) {
      return resJson(res, { isLogin: true });
    } else {
      return resJson(res, { isLogin: false }, '未登录');
    }
  }
};

controller.logout = {
  method: 'get',
  action: function(req, res, next) {
    if (req.session && req.session.user) {
      req.session.user = null;
    }
    return resJson(res);
  }
};

module.exports = controller;
